<template>
  <ga-drawer class="" :width="1100" :visible="visible" @cancel="onClose">
    <template #title>
      <div class="drawer-title-wrap">
        <div class="rel-title">
          <div class="rel-title-name text-ellipsis" :title='type === "workload"
            ? detailInfo?.srcWorkloadName
            : detailInfo?.srcPodName
            '>
            {{ type === "workload"
              ? detailInfo?.srcWorkloadName
              : detailInfo?.srcPodName }}
          </div>
          <div>-&gt;</div>
          <div class="rel-title-name text-ellipsis" :title='type === "workload"
            ? detailInfo?.dstWorkloadName
            : detailInfo?.dstPodName
            '>
            {{ type === "workload"
              ? detailInfo?.dstWorkloadName
              : detailInfo?.dstPodName }}
          </div>
        </div>
        <div class="sub-time-title">
          {{ dayjs(Number(detailInfo?.requestTimeStamp)).format(msDateTime) }} -
          {{ dayjs(
            Number(detailInfo?.requestTimeStamp) +
            Number(detailInfo?.requestTotalTime) / 1000000
          ).format(msDateTime) }}
        </div>
        
        <icon-undo class="title-back" v-show="detailList.length > 0" @click="backPreDetail" />
      </div>
    </template>
    <div class="mb10">
      <ga-radio-group type="button" v-model="activeTab">
        <ga-radio value="request">请求详情</ga-radio>
        <ga-radio value="relate">关联分析</ga-radio>
        <ga-radio value="flame">火焰图</ga-radio>
      </ga-radio-group>
    </div>
    <div v-show="activeTab === 'request'">
      <RequestTab
        v-bind="{ appChartLoading, appChartsOptions, netChartsOptions, netChartLoading, detailInfo, exceptionTime }"  @select-topo-edge="selectTraceEdge" />
    </div>
    <div v-show="activeTab === 'relate'">
      <RelationTab v-bind="{ relateLoading, relateList, detailInfo, maxSize, visible }" @go-next-detail="nextDetail" />
    </div>
    <div v-show="activeTab === 'flame'">
      <FlameGraph v-bind="flameProps" />
    </div>
  </ga-drawer>
</template>

<script setup>
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import dayjs from 'dayjs';
import RequestTab from './RequestTab.vue';
import RelationTab from './RelationTab.vue';
import FlameGraph from '@/components/FlameGraph/FlameGraph.vue';
import { getExceptionChartsData, getExceptionTimeData, queryReceiverPackageLine, querySendPackageLine, querySessionCountLine, queryZeroWindowLine } from '@/api/exceptionDetail';
import { basiclineOption } from '@/utils/chartOption';

import { cloneDeep } from 'lodash'
import useRequestTab from './hooks/useRequestTab';
import { buildChartData } from './service';
import useRelationTab from './hooks/useRelationTab';
import { isEmpty } from 'lodash';

const msDateTime = "YYYY-MM-DD HH:mm:ss.SSS";
const props = defineProps({
  visible: Boolean,
  listParams: {
    type: Object,
    default: () => ({})
  },
  maxSize: Number,
  type: String,
  nowDetail: {
    type: Object,
    default: () => ({})
  }
})
const emits = defineEmits(['on-cancel'])

const activeTab = ref('request')
const detailInfo = ref(props.nowDetail)
const detailList = ref([])
const exceptionTime = ref()
const { appChartLoading,
  appChartsOptions,
  netChartLoading,
  netChartsOptions,
  getAppChartsData,
  getNetChartsData } = useRequestTab({ props, detailInfo })
const { relateLoading, relateList, getRelateList } = useRelationTab({ props, detailInfo })
// 获取异常请求耗时数据
const getTimeData = () => {
  const listParams = props.listParams
  console.log(detailInfo.value?.id, 'detailInfo');

  const params = {
    masterIp: listParams.masterIps?.join(),
    traceId: detailInfo.value?.id,
    from: listParams.startTime,
    to: listParams.endTime,
  };
  getExceptionTimeData(params).then((res) => {
    exceptionTime.value = res.data || {}
  });
};
// 关联分析中查看请求详情，当前详情抽屉信息更新为要查看的请求，同时将上一个请求详情信息push到detailList中
const nextDetail = (record) => {

  detailList.value.push(detailInfo)
  detailInfo.value = record

  // setDetailList(list);
  activeTab.value = 'request'
};
const backPreDetail = () => {
  const detail = detailList.value.pop();
  detailInfo.value = detail

  activeTab.value = 'request'
};
const clearNetChartStyle = () => {
  const netChartTitle = document.getElementById("netChartTitle");
  if (netChartTitle) {
    netChartTitle.classList.remove("focused-view");
  }
};
const onClose = () => {
  activeTab.value = 'request'
  detailInfo.value = {}
  detailList.value = []
  emits('on-cancel')
  exceptionTime.value = {}
}
const flameProps = computed(() => {
  return {
    activeItem: {

      ...detailInfo.value,
      tid: exceptionTime.value?.tid, pid: exceptionTime.value?.pid,
    },
    isActive: activeTab.value === 'flame'
  }
})
const selectTraceEdgeNetChange = async (params, netParams) => {
  const { listParams, maxSize } = props

  params = {
    ...params,
    startPage: 1,
    size: maxSize,
    startTime: listParams.startTime,
    endTime: listParams.endTime,
    masterIps: listParams.masterIps,
  };
  netParams = {
    ...netParams,
    from: listParams.startTime,
    to: listParams.endTime,
  };
  const queryList = [
    getExceptionChartsData(params),
    querySessionCountLine(netParams, "workload"),
  ];
  if (
    !(
      detailInfo?.srcWorkloadKind === "vm" &&
      detailInfo.dstWorkloadKind === "vm"
    )
  ) {
    queryList.push(
      queryZeroWindowLine(netParams, "workload"),
      querySendPackageLine(netParams, "workload"),
      queryReceiverPackageLine(netParams, "workload")
    );
  }
  const results = await Promise.all(queryList);
  const [res, scRes, zwRes, spcRes, rpcRes] = results;

  const { packetLoss, retransmit, rttsum } = res.data;
  netChartsOptions.value = {
    packetLoss: buildChartData(packetLoss || [], "丢包数", "", true),
    retransmit: buildChartData(retransmit || [], "重传数", "", true),
    rttsum: buildChartData(rttsum || [], "SRTT", "us", true),
    zeroWindow: zwRes
      ? buildChartData(
        zwRes.data?.lineChartVos || [],
        "0窗口",
        "",
        true
      )
      : cloneDeep(basiclineOption),
    sessionCount: buildChartData(
      scRes.data?.lineChartVos || [],
      "活跃会话数",
      "",
      true
    ),
    sendPackage: spcRes
      ? buildChartData(
        spcRes.data?.lineChartVos || [],
        "发包数",
        "",
        true
      )
      : cloneDeep(basiclineOption),
    receiverPackage: rpcRes
      ? buildChartData(
        rpcRes.data?.lineChartVos || [],
        "收包数",
        "",
        true
      )
      : cloneDeep(basiclineOption),
  };
  netChartLoading.value = false
};
const selectTraceEdgeAppChange = async (params) => {
  // setAppChartLoading(true);
  appChartLoading.value = true
  params = {
    startPage: 1,
    size: maxSize,
    startTime: listParams.startTime,
    endTime: listParams.endTime,
    masterIps: listParams.masterIps,
    ...params,
    // contentKey: detailInfo?.contentKey,
  };
  if (!detailInfo?.contentKey) {
    params.dstPort = detailInfo?.dstPort;
    params.dstIP = detailInfo?.dstIP?.substring(
      0,
      detailInfo?.dstIP?.indexOf(":")
    );
  }
  getExceptionChartsData(params)
    .then((res) => {
      const { errorRate, requestTotal, responseTime } = res.data.data;
      appChartsOptions.value = ({
        reqChartOptions: buildChartData(
          requestTotal || [],
          "请求量",
          "",
          true
        ),
        errChartOptions: buildChartData(
          errorRate || [],
          "错误率",
          "100%",
          true
        ),
        resChartOptions: buildChartData(
          responseTime || [],
          "响应时间",
          "ns",
          true
        ),
      });
    })
    .finally(() => {
      appChartLoading.value = false
    });
};
const selectTraceEdgeTimeChange = (params) => {
  const { listParams } = props
  params = {
    masterIp: listParams.masterIps?.join(),
    ...params,
    from: listParams.startTime,
    to: listParams.endTime,
  };
  getExceptionTimeData(params).then((res) => {
    exceptionTime.value = res.data || {}
  });
};
const selectTraceEdge = (params, netParams, timeParams) => {
  selectTraceEdgeNetChange(params, netParams);
  selectTraceEdgeAppChange(params);
  selectTraceEdgeTimeChange(timeParams);
};
watch(() => props.nowDetail, (newV) => {
  if (props.visible) {
    detailInfo.value = newV
  }
})
watch([() => props.visible, detailInfo], ([visible]) => {
  if (visible && !isEmpty(detailInfo.value)) {

    getAppChartsData()
    getNetChartsData()
    getRelateList()
    getTimeData()
  }
})
onMounted(() => {
  window.addEventListener('click', clearNetChartStyle)
})
onUnmounted(() => {
  window.removeEventListener('click', clearNetChartStyle)
})
</script>

<style scoped lang="scss">
// 详情侧边栏的样式
.drawer-title-wrap {
  display: flex;
  align-items: flex-end;
  flex: 1;

  .rel-title {
    font-weight: 500;
    font-size: 16px;
    color: var(--default-text-color);
    margin-right: 20px;
    display: flex;
    align-items: center;

    .rel-title-name {

      max-width: 180px;
    }
  }

  .sub-time-title {
    font-size: 12px;
    font-weight: 400;
    line-height: 20px;
    color: var(--body-text-color);
  }

  .title-back {
    margin-left: auto;
    cursor: pointer;
  }
}
</style>
